'use strict'

###*
 # @ngdoc directive
 # @name xoceanApp.directive:subjectBox
 # @description
 # # subjectBox
 # used in '/#/wizard/step_3'
###
angular.module('xoceanApp')
  .directive('subjectBox', ($rootScope, $compile, $state, $stateParams, $window, $interval, Subject)->
    restrict: 'E'
    transclude: true
    scope: true
    link: (scope, element, attrs) ->
      return if not scope.html
      element.html('')
      element.append $compile(scope.html)(scope)

      saveAutomatically = ->
        _html = element.html()
        subjectModel = {
          html: element.html()
        }
        angular.extend(subjectModel, scope.basicInfo)
        Subject.saveAutomatically(subjectModel)

      if not $stateParams.subjectId
        stop = $interval saveAutomatically, 1000*60*2
        element.on '$destroy', ->
          $interval.cancel(stop)
          return

        scope.$on 'quit',(e)->
          saveAutomatically()
          Subject.deleteSubjectById(scope.basicInfo.modelid, false)
          return


      # 保存专题
      scope.$parent.uploadSubject = ->
        _html = element.html()
        scope.$parent.$parent.html = _html
        el = document.createElement('div')
        el.innerHTML = _html
        el.querySelector('.js-tie-vm')?.textContent = "$comment"
        subjectModel = {
          html: el.innerHTML
        }
        angular.extend(subjectModel, scope.basicInfo)
        Subject.upload(subjectModel).then (data)->
          console.log 'upload done!'
          Subject.deleteSubjectInLocal(subjectModel.modelid)
          scope.$parent.$parent.pageLink = data.url or 'http://www.163.com'
          $state.go('xocean.wizard.finish')
          return

        return
      
      # 预览专题
      scope.$parent.previewSubject = ->
        _html = element.html()
        subjectModel = {
          html: element.html()
        }
        angular.extend(subjectModel, scope.basicInfo)
        Subject.preview(subjectModel).then (data)->
          el = document.createElement('div')
          el.innerHTML = data
          [].slice.call(el.querySelectorAll('script,link')).forEach (item)->
            if item.src
              item.src = item.src.replace(/http:\/\/img[1-6]\.cache\.netease\.com\/.*\//, '/xocean/preview/')
            if item.href            
              item.href = item.href.replace(/http:\/\/img[1-6]\.cache\.netease\.com\/.*\//, '/xocean/preview/')
          
          newWindow = $window.open('','','channelmode=no, location=no, menubar=no, scrollbars=yes')
          newWindow.document.write(el.innerHTML)
          return
        return

      # 返回上一步
      scope.$parent.prevStep = ->
        _html = element.html()
        scope.$parent.$parent.html = _html
        scope.$parent.$parent.isEditing = true
        $state.go('xocean.wizard.basicInfo')
        return

      return
  )
